package cn.com.lyb;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileMD5Calculator {

    public static void main(String[] args) {
        //String filePath = "C:\\Users\\85438\\Desktop\\1.txt"; // ce320c4dc58a313068df20c8fa28001c
        String filePath = "C:\\Users\\85438\\Desktop\\2.txt"; //   ce320c4dc58a313068df20c8fa28001c
        File file = new File(filePath);
        System.out.println(file.getPath());
        System.out.println(file.getName());
//        try {
//            String md5 = calculateMD5(filePath);
//            System.out.println("MD5: " + md5);
//        } catch (IOException | NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
    }

    private static String calculateMD5(String filePath) throws IOException, NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        try (FileInputStream fis = new FileInputStream(filePath)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = fis.read(buffer, 0, buffer.length)) != -1) {
                digest.update(buffer, 0, bytesRead);
            }
        }

        byte[] hash = digest.digest();
        StringBuilder hexString = new StringBuilder();

        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        return hexString.toString();
    }
}
